package com.gitee.zw.irmp.common.auth.session;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gitee.zw.irmp.common.auth.vo.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;

import java.time.Duration;


@Slf4j
public class UserSessionStoreRedisImpl implements UserSessionStore {

    public static final String IRMP_SSO_TOKEN_PRE = "IRMP-SSO-TOKEN:";
    @Autowired private RedisTemplate<String, LoginUser> userStore;
    @Autowired private ObjectMapper objectMapper;


    @Value("${app.irmp.common.auth.jwt.cookie-timeout:60}")
    public void setTimeoutMinutes(int timeoutMinutes) {
        timeout = Duration.ofMinutes(timeoutMinutes);
    }
    private Duration timeout;
    @Override
    public LoginUser getLoginUser(String token) {
        LoginUser loginUser = userStore.opsForValue().getAndExpire(IRMP_SSO_TOKEN_PRE + token, timeout);
        if (loginUser == null) {
            log.debug("User not found in redis for token: {}", token);
        }
        return loginUser;
    }
    @Override
    public void setLoginUser(String token, LoginUser loginUser) {
        userStore.opsForValue().set(IRMP_SSO_TOKEN_PRE + token, loginUser, timeout);
    }
}
